import { AddPositionBean, PositionItem, UpdatePositionBean } from "../../Position/data";
import { useRef, useState } from "react";
import { Button, Divider, Modal, message } from "antd";
import { DepartmentItem } from "../data";
import { addPosition, deletePosition, queryPositionByDepId, updatePosition } from "../../Position/service";
import { SUCCESS_CODE } from "@/utils/request";
import { PlusOutlined } from "@ant-design/icons";
import AddPositionForm from "./AddPositionForm";
import UpdatePositionForm from "./UpdatePositionForm";
import ProTable, { ActionType, ProColumns } from "@ant-design/pro-table";

interface DepartmentProps {
    department: DepartmentItem;
    visible: boolean;
    onClose: () => void;
}

export default (props: DepartmentProps) => {
    const {
        visible,
        onClose,
        department,
    } = props;

    const [parentPositionId, setParentPositionId] = useState<string | undefined>(undefined);
    const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false)
    const [positionData, setPositionData] = useState<PositionItem>()
    const actionRef = useRef<ActionType>();

    function convertData(data: { id: any; name: any; department_id: any; next_level: string | any[] }) {
        const node = {
            id: data.id,
            name: data.name,
            department_id: data.department_id,
            children: [] as any,
        };
        if (data.next_level && data.next_level.length > 0) {
            for (let i = 0; i < data.next_level.length; i++) {
                const child = convertData(data.next_level[i]);
                node.children.push(child);
            }
        }
        return node;
    }

    const addPositionEvent = async (values: AddPositionBean) => {
        const res = await addPosition(values);
        if (res.code === SUCCESS_CODE) {
            message.success('添加成功');
            actionRef.current?.reload()
            handleAddModalVisible(false)
        } else {
            message.error(res.message || '添加失败');
        }
    }

    const updatePositionEvent = async (values: UpdatePositionBean) => {
        const res = await updatePosition(values);
        if (res.code === SUCCESS_CODE) {
            message.success('修改成功');
            actionRef.current?.reload()
            handleUpdateModalVisible(false)
        } else {
            message.error(res.message || '修改失败');
        }
    }

    const columns: ProColumns<PositionItem>[] = [
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '职位名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '操作',
            dataIndex: 'options',
            key: 'opsitons',
            render: (_, record) => {
                const onClickRemove = () => {
                    const { id, name } = record;
                    Modal.confirm({
                        title: `删除职位 ${id}`,
                        content: (
                            <>
                                <Divider />
                                <p>确认要删除职位</p>
                                <span style={{ fontWeight: 'bolder' }}>{name}</span>
                                &nbsp;&nbsp;?
                            </>
                        ),
                        okText: '确定',
                        cancelText: '取消',
                        onOk: async () => {
                            await deletePosition(id);
                            message.success("删除成功,请刷新后查看")
                        },
                        centered: true,
                        width: '30vw',
                        style: { height: '15vw' },
                    });
                };
                return (
                    <>

                        <Divider type="vertical" />
                        <a onClick={() => {
                            setParentPositionId(record.id)
                            handleAddModalVisible(true)
                        }}>
                            添加子职位
                        </a>
                        <Divider type="vertical" />
                        <a onClick={() => {
                            setPositionData(record)
                            handleUpdateModalVisible(true)
                        }}>
                            编辑
                        </a>
                        <Divider type="vertical" />
                        <a onClick={onClickRemove}>删除</a>
                        <Divider type="vertical" />
                    </>
                )
            }
        }
    ];

    return (
        <Modal
            title={<div>{department.name} &nbsp;职位列表</div>}
            open={visible}
            width={1200}
            footer={null}
            centered
            destroyOnClose
            onOk={() => onClose()}
            onCancel={() => onClose()}
            afterClose={() => onClose()}
        >
            <Button key={''} type="primary" onClick={() => {
                handleAddModalVisible(true)
                setParentPositionId(undefined)
            }}>
                <PlusOutlined /> 添加
            </Button>
            <ProTable<PositionItem>
                search={false}
                actionRef={actionRef}
                columns={columns}
                request={async () => {
                    const res = await queryPositionByDepId(department.id);
                    const result: PositionItem[] = [];
                    if (res.code === SUCCESS_CODE) {
                        const data = res?.data;
                        if (data && data.length > 0) {
                            for (let i = 0; i < data.length; i++) {
                                result.push(convertData(data[i]));
                            }
                        }
                    } else {
                        message.error(res.message)
                    }
                    res.data = result

                    return res;
                }}
                style={{ marginTop: '20px' }}
            />

            {addModalVisible && (
                <AddPositionForm
                    department={department}
                    pid={parentPositionId}
                    onSubmit={addPositionEvent}
                    onCancel={() => handleAddModalVisible(false)}
                    modalVisible={addModalVisible}
                    visibleHandler={() => handleAddModalVisible(false)}
                />
            )}
            {updateModalVisible && positionData && (
                <UpdatePositionForm
                    position={positionData}
                    onSubmit={updatePositionEvent}
                    onCancel={() => handleUpdateModalVisible(false)}
                    modalVisible={updateModalVisible}
                    visibleHandler={() => handleUpdateModalVisible(false)}
                />
            )}
        </Modal>
    )

}